<template>
  <view class="add-product-container">
    <!-- 顶部搜索栏 -->
    <view class="search-bar">
      <view class="search-input-wrapper">
        <uni-icons type="search" size="20" color="#999"></uni-icons>
        <input 
          class="search-input" 
          type="text" 
          placeholder="请输入商品名称" 
          v-model="searchKeyword"
          @input="handleSearch"
        />
        <view class="clear-btn" v-if="searchKeyword" @click="clearSearch">
          <uni-icons type="clear" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>
    
    <!-- 商品列表 -->
    <scroll-view
      class="product-scroll" 
      scroll-y
      lower-threshold="50"
      enable-back-to-top
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
      @scrolltolower="loadMoreProducts"
      :scroll-top="scrollTop"
      @scroll="onScroll"
    >
       <!-- 加载状态 -->
        <view class="loading-state" v-if="loading && filteredProductList.length === 0">
          <text class="loading-text">正在加载商品数据...</text>
        </view>
        
        <view class="product-list" v-if="!loading || filteredProductList.length > 0">
          <!-- 商品卡片 -->
          <view
            class="product-card" 
            v-for="(product, index) in filteredProductList" 
            :key="product.rowid"
          >
        
            <!-- 描述区域 -->
            <view class="product-info">
              <text class="product-name">{{ product['686e27a8602f55a03053a3ba'] }}：{{ product['68e75e626f2593f630363411'] }}</text>
              <text class="product-code">{{ product['ctime'] }}</text>
            </view>

            <view>{{ product['686e27b3602f55a03053a3c0'] }}</view>
            
          </view>
          
          <!-- 空状态 -->
          <view class="empty-state" v-if="filteredProductList.length === 0 && !loading">
            <text class="empty-text">暂无流水数据</text>
          </view>
          
          <!-- 加载更多提示 -->
          <view class="load-more" v-if="filteredProductList.length > 0">
            <text class="load-more-text" v-if="loadingMore">正在加载更多...</text>
            <text class="load-more-text" v-else-if="noMoreData">没有更多数据了</text>
            <text class="load-more-text" v-else-if="loadMoreError" @click="loadMoreProducts">加载失败，点击重试</text>
          </view>
        </view>
    </scroll-view>

  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import http from '../../../utils/request'
import { callWorkflowListAPI, callWorkflowAPI, callWorkflowListAPIPaged } from '../../../utils/workflow'
import { useUserStore } from '../../../store/user'
import { onLoad, onReady, onUnload, onShow, onBackPress } from '@dcloudio/uni-app'
import { useTaskStore } from '../../../store/task'


const taskStore = useTaskStore()

// 搜索关键词
const searchKeyword = ref('')

// 商品列表数据
const productList = ref([
  {
    name: "杭州火绒有限公司",
    status1: "已支付",
    status2: "线下支付",
    ctime: "2025-09-08",
    amount: "1000.00",
  }
])

// 加载状态
const loading = ref(false)
const loadingMore = ref(false)
const noMoreData = ref(false)
const loadMoreError = ref(false)
const refreshing = ref(false)

// 分页参数
const pageNum = ref(1)
const pageSize = ref(10)
const totalCount = ref(0)

// 滚动位置
const scrollTop = ref(0)

// 过滤后的商品列表 - 只保留入库或出库的数据
const filteredProductList = computed(() => {
  return productList.value.filter(product => {
    const transactionType = product["686e27a8602f55a03053a3ba"]
    return transactionType === '入库' || transactionType === '出库'
  })
})

// 滚动事件处理
const onScroll = (e) => {
  scrollTop.value = e.detail.scrollTop
}




// 处理搜索
const handleSearch = () => {
  // 搜索时重置数据并重新加载
  resetData()
  getProductData(false, true)
}

// 清除搜索
const clearSearch = () => {
  searchKeyword.value = ''
}

// 加载更多商品 - 独立的加载更多方法
const loadMoreProducts = () => {
  console.log('加载更多商品');
  if (loadingMore.value || noMoreData.value || loadMoreError.value) {
    return
  }
  
  // 添加防抖处理，避免频繁触发
  setTimeout(() => {
    loadMoreProductData()
  }, 300)
}

// 独立的加载更多数据方法
const loadMoreProductData = async () => {
  try {
    loadingMore.value = true
    loadMoreError.value = false
    
    // 计算下一页的页码
    const nextPageNum = pageNum.value + 1
    
    const result = await callWorkflowListAPIPaged('6865028d4e2949f4119927aa', [], pageSize.value, nextPageNum, 0) 
    
    if(result && result.data) {
      console.log('加载更多流水数据:', result.data)
      
      // 追加数据到现有列表
      if (result.data.length > 0) {
        productList.value = [...productList.value, ...result.data]
        // 只有在数据加载成功后才更新页码
        pageNum.value = nextPageNum
      }
      
      // 检查是否还有更多数据
      if (result.data.length < pageSize.value || productList.value.length >= result.total) {
        noMoreData.value = true
      }
      
    } else {
      loadMoreError.value = true
    }
  } catch (error) {
    console.error('加载更多流水数据失败:', error)
    loadMoreError.value = true
  } finally {
    loadingMore.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  refreshing.value = true
  pageNum.value = 1
  noMoreData.value = false
  loadMoreError.value = false
  scrollTop.value = 0 // 刷新时重置滚动位置
  getProductData(true)
}

// 重置数据
const resetData = () => {
  productList.value = []
  pageNum.value = 1
  totalCount.value = 0
  noMoreData.value = false
  loadMoreError.value = false
  scrollTop.value = 0 // 重置滚动位置
}





// 获取商品数据 - 专注于初始加载和刷新
const getProductData = async (isRefresh = false) => {
  try {
    if (isRefresh) {
      refreshing.value = true
    } else {
      loading.value = true
    }
    let result = {}
    if(!searchKeyword.value || searchKeyword.value.trim() === '') {
       // 初始加载和刷新都使用第1页
    result = await callWorkflowListAPIPaged('6865028d4e2949f4119927aa', [], pageSize.value, 1, 0) 
    }else{
        // 初始加载和刷新都使用第1页
     result = await callWorkflowListAPIPaged('6865028d4e2949f4119927aa', [{
          "controlId": "686e28f4602f55a03053a3dc",
          "dataType": 29,
          "spliceType": 1,
          "filterType": 1,
          "values": [searchKeyword.value]
        }], pageSize.value, 1, 0) 
    }
    
    if(result && result.data) {
      console.log('流水数据:', result.data)
      
      // 首次加载或刷新
      productList.value = result.data
      totalCount.value = result.total || 0
      pageNum.value = 1 // 重置为第一页
      noMoreData.value = result.data.length < pageSize.value || result.total <= pageSize.value
      
    } else {
      uni.showToast({
        title: '获取流水数据失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取流水数据失败:', error)
    uni.showToast({
      title: '获取流水数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 跳转到商品详情页
const goToProductDetail = (product) => {
  // 保存当前滚动位置
  uni.setStorageSync('productListScrollTop', scrollTop.value)
  uni.navigateTo({
    url: `/pages/warehouse/product/detail?rowid=${product.rowid}`
  })
}



watch(() => taskStore.pendingTaskUpdate, (newVal) => {
  if (newVal) {
    resetData()
    getProductData()
    // 清除待更新任务
    taskStore.clearPendingTaskUpdate()
  }
})

onLoad(async () => {
  // 页面加载时可以从服务器获取商品数据
  resetData()
  await getProductData()
})

onShow(() => {
  // 恢复滚动位置
  const savedScrollTop = uni.getStorageSync('productListScrollTop')
  if (savedScrollTop) {
    scrollTop.value = savedScrollTop
    uni.removeStorageSync('productListScrollTop')
  }
})



</script>

<style lang="scss" scoped>
.add-product-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
  
  .search-bar {
    background-color: #ffffff;
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    
    .search-input-wrapper {
      display: flex;
      align-items: center;
      background-color: #f8f8f8;
      border-radius: 32rpx;
      padding: 20rpx 30rpx;
      
      .search-input {
        flex: 1;
        margin-left: 20rpx;
        font-size: 28rpx;
        color: #333333;
        
        &::placeholder {
          color: #999999;
        }
      }
      
      .clear-btn {
        margin-left: 20rpx;
        padding: 10rpx;
      }
    }
  }
  
  .product-scroll {
    height: calc(100vh - 200rpx); /* 减去搜索栏和底部按钮的高度 */
    background-color: #f5f5f5;
    
    /* 滚动条样式优化 */
    &::-webkit-scrollbar {
      width: 6rpx;
    }
    
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
      border-radius: 3rpx;
    }
    
    &::-webkit-scrollbar-thumb {
      background: #c1c1c1;
      border-radius: 3rpx;
    }
    
    &::-webkit-scrollbar-thumb:hover {
      background: #a8a8a8;
    }
    
    .loading-state {
      padding: 100rpx 0;
      text-align: center;
      
      .loading-text {
        color: #999999;
        font-size: 28rpx;
      }
    }
    
    .product-list {
      padding: 20rpx 30rpx 180rpx;
      
      .product-card {
        background-color: #ffffff;
        border-radius: 16rpx;
        padding: 30rpx;
        margin-bottom: 20rpx;
        display: flex;
        align-items: center;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
        
    
     
        
        .product-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          overflow: hidden;
          
          .product-name {
            font-size: 32rpx;
            font-weight: bold;
            color: #333333;
            margin-bottom: 12rpx;
            line-height: 1.4;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
          
          .product-code {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .product-spec {
            font-size: 24rpx;
            color: #666666;
            margin-bottom: 8rpx;
          }
          
          .unavailable-stock {
            font-size: 24rpx;
            color: #ff4757;
            margin-bottom: 8rpx;
          }
          
          .available-stock {
            font-size: 24rpx;
            color: #2ed573;
          }
        }
      }
      
      .empty-state {
        padding: 100rpx 0;
        text-align: center;
        
        .empty-text {
          color: #999999;
          font-size: 28rpx;
        }
      }
      
      .load-more {
        padding: 30rpx 0;
        text-align: center;
        
        .load-more-text {
          color: #999999;
          font-size: 26rpx;
        }
      }
    }
  }
  
 
}
</style>